package com.nerve.secondhandcar.service.impl;

import java.util.List;

import org.ko.core.dao.support.Finder;
import org.ko.core.dao.support.Updater;
import org.ko.core.websupport.page.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.nerve.secondhandcar.dao.BrandDao;
import com.nerve.secondhandcar.domain.Brand;
import com.nerve.secondhandcar.service.BrandService;

/**
 * 平台中的汽车品牌Service接口实现
 * @author 集成显卡
 * @version 2014-10-09 17:26:50
 */
@Service
@Transactional
public class BrandServiceImpl implements BrandService {

	@Autowired
	private BrandDao dao;

	@Override
	public Brand addDo(Brand bean) {
		dao.save(bean);

		return bean;
	}

	/**
	 * 批量删除指定id实例
	 * 先将品牌旗下的汽车的品牌属性设置为null
	 */
	public void delete(Long[] ids) {
		String hql = "update Car set brand = null where brand.id";
		for(Long l:ids){
			Brand b = dao.get(l);
			if(b!=null){
				//判断是否为父品牌
				if(b.getParent()==null){
					dao.runHql(hql+" in (select b.id FROM Brand as b where b.parent.id="+b.getId()+")");
				}
				else{
					dao.runHql(hql+" = "+b.getId());
				}
				
				dao.delete(b);
			}
		}
		//dao.delete(ids);
	}

	public Brand editDo(Brand bean) {
		
		Updater<Brand> updater = new Updater<Brand>(bean);
		updater.exclude("parent");
		Brand ret = dao.updateByUpdater(updater);
		return ret;
	}

	@Override
	public Page findPage(Page p,String searchText) {
		return dao.findPage(p.getPageNo(), p.getPageSize(),searchText);
	}
	

	@Override
	public List findTree(String searchText) {
		return dao.findTree(searchText);
	}
	
	public List findAuthBrands() {
		return dao.findAuthBrands();
	}

	public boolean changeParent(Long id, Long pid) {
		int re = dao.changeParent(id,pid);
		
		return re>0;
	}

	@Override
	public Brand get(Long id) {
		return dao.get(id);
	}

	@Override
	public List<Brand> findForSelect() throws Exception {
		Finder f = Finder.create("FROM Brand where parent = null order by firstLetter asc");
		List<Brand> brandList = dao.find(f);
		
		return brandList;
	}
}